package customer

import (
	rich_err "app/error"
	"app/models"
	"app/service"
	"errors"

	"github.com/jinzhu/gorm"

	"github.com/gin-gonic/gin"
)

func Gets(context *gin.Context) ([]*models.Customer, *models.Pager, *rich_err.RichError) {
	base := models.Orm.Model(&models.Customer{}).
		Select("customer.*")
	results, pager, err := service.GetDetails[models.Customer](context, base, models.Customer{}.TableName(), map[string]string{})
	if err != nil {
		return nil, nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return results, pager, nil
}

func Get(context *gin.Context) (*models.Customer, *rich_err.RichError) {
	data, err := service.Get[models.Customer](context)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return data, nil
}

func Create(context *gin.Context) (*models.Customer, *rich_err.RichError) {
	req := new(models.CustomerCore)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	data := models.Customer{CustomerCore: *req}
	result := models.Orm.Create(&data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	return &data, nil
}

func Update(context *gin.Context) (*models.Customer, *rich_err.RichError) {
	req := new(models.CustomerDelta)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}

	data, err := service.Get[models.Customer](context)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	if req.Name != nil {
		data.Name = req.Name.(string)
	}

	if req.Phone != nil {
		data.Phone = req.Phone.(string)
	}

	if req.Address != nil {
		data.Address = req.Address.(string)
	}

	if req.Remark != nil {
		data.Remark = req.Remark.(string)
	}
	result := models.Orm.Save(data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	return data, nil
}

func Delete(context *gin.Context) *rich_err.RichError {
	data, err := service.Get[models.Customer](context)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil
		}
		return rich_err.NewError(rich_err.RequestInvalid, err)
	}
	result := models.Orm.Delete(data)
	if result.Error != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	return nil
}
